package aole.util;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

public class Clipboard {
	public static Image readImage() {
		Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard()
				.getContents( null );

		try {
			if( t != null && t.isDataFlavorSupported( DataFlavor.imageFlavor ) ) {
				Image image = (Image) t
						.getTransferData( DataFlavor.imageFlavor );
				return image;
			}
		} catch( UnsupportedFlavorException | IOException e ) {}

		return null;
	}

	public static void saveImage( Image image ) {
		if( image == null ) return;

		ImageTransferable transferable = new ImageTransferable( image );
		Toolkit.getDefaultToolkit().getSystemClipboard()
				.setContents( transferable, null );
	}

	static class ImageTransferable implements Transferable {
		private Image	image;

		public ImageTransferable( Image image ) {
			this.image = image;
		}

		public Object getTransferData( DataFlavor flavor )
				throws UnsupportedFlavorException {
			if( isDataFlavorSupported( flavor ) ) {
				return image;
			} else {
				throw new UnsupportedFlavorException( flavor );
			}
		}

		public boolean isDataFlavorSupported( DataFlavor flavor ) {
			return flavor == DataFlavor.imageFlavor;
		}

		public DataFlavor[] getTransferDataFlavors() {
			return new DataFlavor[] { DataFlavor.imageFlavor };
		}
	}
}